<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\general\LihuaCity;
use app\common\model\Version;
use think\Db;
use OSS\Core\OssException;
use OSS\OssClient;
use fast\Http;
use think\Cookie;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init', 'uppic', 'checkversion','text_init', 'walletpayfreedata'];
    protected $noNeedRight = '*';
    protected $_err = '';
	
	
	public function checkversion(){
		$v1 = $this->request->request('v1');
		$v2 = $this->request->request('v2');
		echo version_compare($v1,$v2);
	}

    /**
     * 加载初始化
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="version", type="string", required=true, description="版本号, 如：1.1.1")
     * @ApiReturn   ({"code":1,"msg":"","time":"1571643206","data":{"versiondata":{"enforce":1,"version":"0.0.9","newversion":"1.0.0","downloadurl":"https:\/\/www.baidu.com","packagesize":"20M","upgradetext":"更新内容"},"city_list":[{"id":3,"name":"常州","store_list":[{"id":17,"name":"鸣新","addr":"","lng":null,"lat":null},{"id":18,"name":"湖塘","addr":"","lng":null,"lat":null},{"id":27,"name":"火车站","addr":"","lng":null,"lat":null},{"id":28,"name":"城北","addr":"常州市新北区太湖中路71号附近","lng":"31.822805","lat":"119.974824"}]},{"id":4,"name":"南京","store_list":[{"id":19,"name":"白下路","addr":"","lng":null,"lat":null},{"id":21,"name":"瑞金路","addr":"","lng":null,"lat":null},{"id":24,"name":"虹桥","addr":"","lng":"0.000000","lat":"0.000000"},{"id":26,"name":"徐庄","addr":"","lng":null,"lat":null},{"id":29,"name":"黄山路","addr":"","lng":null,"lat":null}]}]}})
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $content = [
                'versiondata' 			=> Version::check($version),
                // 'versiondata' 			=> null,
                'city_list'   			=> LihuaCity::getCityAndStoreList(),
				'remark'      			=> ['无接触配送'],
				'remark_placeholder'	=> '可以选择【无接触配送】'
            ];
            $this->success('OK', $content);
        } else {
            $this->error('参数错误');
        }
    }

    /**
     * 测试接口——加载初始化
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="version", type="string", required=true, description="版本号, 如：1.1.1")
     * @ApiReturn   ({"code":1,"msg":"","time":"1571643206","data":{"versiondata":{"enforce":1,"version":"0.0.9","newversion":"1.0.0","downloadurl":"https:\/\/www.baidu.com","packagesize":"20M","upgradetext":"更新内容"},"city_list":[{"id":3,"name":"常州","store_list":[{"id":17,"name":"鸣新","addr":"","lng":null,"lat":null},{"id":18,"name":"湖塘","addr":"","lng":null,"lat":null},{"id":27,"name":"火车站","addr":"","lng":null,"lat":null},{"id":28,"name":"城北","addr":"常州市新北区太湖中路71号附近","lng":"31.822805","lat":"119.974824"}]},{"id":4,"name":"南京","store_list":[{"id":19,"name":"白下路","addr":"","lng":null,"lat":null},{"id":21,"name":"瑞金路","addr":"","lng":null,"lat":null},{"id":24,"name":"虹桥","addr":"","lng":"0.000000","lat":"0.000000"},{"id":26,"name":"徐庄","addr":"","lng":null,"lat":null},{"id":29,"name":"黄山路","addr":"","lng":null,"lat":null}]}]}})
     */
    public function text_init()
    {
        if ($version = $this->request->request('version')) {
            $content = [
                'versiondata' 			=> [
                    "enforce"     => 1,
                    "version"     => $version,
                    "newversion"  => "2.2.2",
                    "downloadurl" => "https://newapp.lihua.com/lihua_app_4.0.3.apk",
                    "packagesize" => "100M",
                    "upgradetext" => "??????"
                ],
                'city_list'   			=> LihuaCity::getCityAndStoreList(),
				'remark'      			=> ['无接触配送', '请加急送'],
				'remark_placeholder'	=> '可以选择【无接触配送】'
            ];
            $this->success('OK', $content);
        } else {
            $this->error('参数错误');
        }
    }

    /*
    * 统计钱包支付中，享受到的优惠金额
    */
    public function walletpayfreedata(){
        $today = date('Y-m');
        $day = $this->request->request('day', $today);
        $sql = "SELECT a.sn as 'sn', a.add_time as 'add_time', a.address as 'address', a.mobile as 'mobile', 
                b.fee as 'fee', a.order_amount as 'order_amount', a.store_name as 'store_name' 
                FROM lihua_order a inner join order_random_fee b ON a.sn =b.order_sn and a.status >=2 and a.pay_type = 3 and a.add_time like '%$day%'";
        $voList = Db::query($sql);
        $_pre=array(
            "sn"            =>  "订单编号",
            "add_time"      =>  "下单时间",
            "address"       =>  "地址",
            "mobile"        =>  "手机号",
            "fee"           =>  "立减金额",
            "order_amount"  =>  "订单金额",
            "store_name"    =>  "分公司",
        );
        $content = $this->getXLSFromList($_pre,$voList);//获得输出的表格内容
        header("Content-type:application/vnd.ms-execl;charset=gb2312");//设置导出格式
        header("Content-Disposition:attactment;filename="."钱包支付随机立减数据统计"."_".$day.".xls");//设置导出文件名
        header("Pragma: no-cache");
        header("Expires: 0");
        echo $content;
        exit;
    }
    //导出excel表
    function getXLSFromList($pres,$lists){
        $keys=array_keys($pres);//获取表头的键名
        $content="";
        $content.="<table border='1'><tr>";
        //输出表头键值
        foreach($pres as $_pre){
            $content.="<td>$_pre</td>";
        }
        $content.="</tr>";
        foreach($lists as $_list){
            $content.= "<tr>";
                foreach($keys as $key){
                    $content.= "<td style='vnd.ms-excel.numberformat:@'>".$_list[$key]."</td>"; //style样式将导出的内容都设置为文本格式 输出对应键名的键值 即内容
                }
            $content.="</tr>";
        }
        $content.="</table>";
        return $content;
    }

    /**
     * 上传图片
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="group", type="string", required=false, description="图片分组，点评为 comment")
     * @ApiParams   (name="file", type="File", required=true, description="文件流")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1571751137","data":{"url":"\/uploads\/comment\/2019\/10\/87915daf04e184df7.jpg"}})
     */
    public function uppic()
    {
        $group = $this->request->post('group', 'default');
        $f = $this->request->file('file');
        if (empty($f)) $this->error('请选择要上传的图片');

        $uploadDir = '/uploads/'. $group .'/'.date('Y/m/');
        $fileInfo  = $f->getInfo();
        $suffix    = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        if (!in_array($suffix, ['jpg','jpeg','png','gif'])) $this->error('图片格式不正确');

        $uniqid    = uniqid(mt_rand(1000,9999));
        $fileName  = $uniqid . '.' . $suffix;
        $picUrl    = $uploadDir . $fileName;
        $picPath   = ROOT_PATH . 'public' . $picUrl;
        $splInfo   = $f->move(ROOT_PATH . 'public' . $uploadDir, $fileName);
        if ($splInfo) {
            switch ($group) {
                case 'comment':
                    $bigPicUrl = $uploadDir . $uniqid . '_big.' . $suffix;
                    copy(ROOT_PATH . 'public' . $picUrl, ROOT_PATH . 'public' . $bigPicUrl);
                    $img = \think\Image::open($picPath);
                    $img->thumb(400, 400, 3)->save($picPath, null, 85);
                    $bigImg = \think\Image::open(ROOT_PATH . 'public' . $bigPicUrl);
                    $bigImg->thumb(1200, 1200)->save(ROOT_PATH . 'public' . $bigPicUrl);
                    $ret = $this->upOss($bigPicUrl);
                    if (!$ret) $this->error($this->_err);
                    $ret = $this->upOss($picUrl);
                    break;

                default:
                    $img = \think\Image::open($picPath);
                    $img->thumb(1200, 1200)->save($picPath);
                    $ret = $this->upOss($picUrl);
                    break;
            }
            if (!$ret) $this->error($this->_err);

        } else {
            $this->error($f->getError());
        }

        $this->success('OK', ['url' => $picUrl]);
    }

    /**
     * 上传文件至阿里oss
     *
     * @param $file
     * @return bool
     */
    protected function upOss($file)
    {
        $keyId     = "LTAI4FbtLusx8NJ78YreYW54";
        $keySecret = "24Ma12hXsg12ERcNG02cLZH0nG4uUb";
        $endpoint  = "http://oss-cn-shanghai.aliyuncs.com";
        $bucket    = "wshtest";
        try {
            $ossClient = new OssClient($keyId, $keySecret, $endpoint);
            $ossClient->uploadFile($bucket, ltrim($file, '/'), ROOT_PATH . 'public' . $file);
        }
        catch (OssException $e) {
            $this->_err = $e->getMessage();
            return false;
        }
        return true;
    }

    // https://open.weixin.qq.com/connect/oauth2/authorize?appid='wx39002761ac0abcba'&redirect_uri=https%3a%2f%2fnewapp.lihua.com%2fcommon%2fwxoauth&response_type=code&scope=snsapi_base&state=#wechat_redirect
    // public function wx_oauth2(){
    //     $api = "https://open.weixin.qq.com/connect/oauth2/authorize?appid='wx39002761ac0abcba'&redirect_uri=https%3a%2f%2fnewapp.lihua.com%2fapi%2fcommon%2fwxoauth&response_type=code&scope=snsapi_base&state=#wechat_redirect";
    //     $ret = Http::post($api);
    //     $res  = json_decode($ret, true);
    //     $this->success('OK', $res);
    // }
    

}
